Nodejs 开发第一个 CLI(命令行界面) 程序

一直拿Node 做Web程序/项目 ,这两天看一些东西看到了数据结构,就想到了当初数据结构作业都是命令行界面的程序,就想Node能不能做呢,就试了试,以下就是成果喽。
切入到一个目录下,新建一个文档为index.js, 如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
var fs = require('fs');
var stdin = process.stdin;
var stdout = process.stdout;

var curDir = process.cwd();
function getDirectoryData(dir){
fs.readdir(dir,function(err,files){
console.log("");
if(!files.length){
return console.log(' \0333[31m No files to show! \033[39m\n');
}
console.log(' Select which file or directory you want to see! \n');

function file(i){
var filename = files[i];

var statFile = fs.statSync(__dirname + '/' + filename);
if(statFile.isDirectory()){
console.log(' '+ ++i + ' \033[31m' + filename + '/\033[39m');
}else{
console.log(' '+ ++i + ' \033[90m' + filename + '\033[39m');
}

if( i == files.length){
read();
}else{
file(i);
}
}

file(0);

function read(){
console.log('');
stdout.write(' \033[33m Enter your choice: \033[39m');
stdin.resume();
stdin.setEncoding('utf8');

stdin.on('data',option);
}

function option(data){
var filename = files[Number(data)-1];
if(fs.statSync(__dirname + '/' + filename).isDirectory()){
stdin.pause();
fs.readdir(__dirname + '/' +filename,function(err,files){
console.log('');
console.log(' (' + files.length + ' files)');
files.forEach(function(file){
console.log(' -- ' + file);
});
console.log('');
})
}else{
stdin.pause();
fs.readFile(__dirname + '/' +filename,'utf8',function(err,data){
console.log('');
console.log('\033[90m' + data.replace(/(.*)/g,' $1') + '\033[39m');
});
}
}
});
}
getDirectoryData(curDir);

以上代码就是实现了一个window dos命令下的一个目录文件查看程序;
DOS CD 到index.js文件所在目录下,运行node index.js,效果如下:

图一 入口
选择1, 回车打开文件如下:

图二
选择7, 回车:

图三

我们进入到磁盘目录下, 看一下我们的文件:

图四

图五

图六

至此,第一个CLI程序结束,后续继续研究,如有不对之处还请指教。

引自: 网易博客(奔跑吧~昭熙小乐)